#ifndef __buttons_h__
#define __buttons_h__

#include <zneo.h>

#define DEBOUNCE 0x07
#define DEBOUNCE_DN(x) (( x & DEBOUNCE) == DEBOUNCE)
#define DEBOUNCE_UP(x) ((~x & DEBOUNCE) == DEBOUNCE)

unsigned short volatile b1up   =0;
unsigned short volatile b1state=0;
unsigned short volatile b2up   =0;
unsigned short volatile b2state=0;
unsigned short volatile b3up   =0;
unsigned short volatile b3state=0;

#define B1PUSHED (b1up > 0 && DEBOUNCE_DN(b1state))
#define B2PUSHED (b2up > 0 && DEBOUNCE_DN(b2state))
#define B3PUSHED (b3up > 0 && DEBOUNCE_DN(b3state))


void InitButtons(void) {
	PDDD |= 0x80; // set PD[3] to In
	PFDD |= 0xC0; // set PF[6,7] to In
}

void CheckButtons(void) {
	b1state <<= 1;
	b2state <<= 1;
	b3state <<= 1;

	if ((PDIN & 0x08) != 0x08){
		b1state |= 0x01;
	}

	if ((PFIN & 0x40) != 0x40){
		b2state |= 0x01;
	}

	if ((PFIN & 0x80) != 0x80){
		b3state |= 0x01;
	}

	if (DEBOUNCE_UP(b1state)) {
		b1up = 1;
	}

	if (DEBOUNCE_UP(b2state)) {
		b2up = 1;
	}

	if (DEBOUNCE_UP(b3state)) {
		b3up = 1;
	}
}


void Init1Button(void) {
	PDDD |= 0x80; // set PD[3] to In
}

void Check1Button(void) {
	b1state <<= 1;
	if ((PDIN & 0x08) != 0x08){
		b1state |= 0x01;
	}
	if (DEBOUNCE_UP(b1state)) {
		b1up = 1;
	}
}

#endif